package hk.m4s.lr.repair.test.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import framework.common.Constant;
import framework.common.zanetwork.core.ResponseCallback;
import framework.common.zanetwork.core.ResponseCode;
import framework.utils.NetWorkUtil;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.UeApp;
import hk.m4s.lr.repair.test.model.AccountModel;
import hk.m4s.lr.repair.test.model.NewsModel;
import hk.m4s.lr.repair.test.model.NewsModelResult;
import hk.m4s.lr.repair.test.model.NewsTabModelResult;
import hk.m4s.lr.repair.test.model.NewsTableModel;
import hk.m4s.lr.repair.test.service.news.NewsService;
import hk.m4s.lr.repair.test.ui.adapter.NewsAdapter;
import hk.m4s.lr.repair.test.ui.webview.WebViewActivity;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import hk.m4s.lr.repair.test.views.listview.VListView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/13.
 * 行业资讯
 */

public class NewsFragment extends Fragment implements View.OnClickListener, VListView.IXListViewListener {
    private Context context;
    private LayoutInflater inflater;
    private TabLayout mTabLayout;
    private VListView vlist;
    private List<NewsModel> newsList = new ArrayList<>();
    private List<NewsTableModel> mTitleList = new ArrayList<NewsTableModel>();//页卡标题集合
    private NewsAdapter newsAdapter;
    private int pageNum = 0;
    private int pageSize = 10;
    private String cloumId = "0";
    private View show_tips;
    private LinearLayout error_reload_btn;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.news_fragment_layout, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        // TODO Auto-generated method stub
        context = getActivity();
        inflater = LayoutInflater.from(context);
        findBaseView();
    }

    private void findBaseView() {
        //添加页卡标题
        mTabLayout = (TabLayout) this.getActivity().findViewById(R.id.tabs);
        vlist = (VListView) this.getActivity().findViewById(R.id.vlist);
        show_tips = (View) this.getActivity().findViewById(R.id.show_tips);
        error_reload_btn = (LinearLayout) this.getActivity().findViewById(R.id.show_tip);
        error_reload_btn.setOnClickListener(this);
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                NewsTableModel model = mTitleList.get(tab.getPosition());
                if (!NetWorkUtil.isNetworkAvaliable(UeApp.getAppContext())) {
                    show_tips.setVisibility(View.VISIBLE);
                    if (newsAdapter != null) {
                        newsAdapter.list.clear();
                        newsAdapter.notifyDataSetChanged();
                    }
                } else {
                    show_tips.setVisibility(View.GONE);
                    cloumId = String.valueOf(model.getId());
                    newsList.clear();
                    getNewList("1", cloumId);
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        newsAdapter = new NewsAdapter(context, newsList);
        vlist.setAdapter(newsAdapter);
        vlist.setXListViewListener(this);
        vlist.setOnItemClickListener(clickItem);
        if (!NetWorkUtil.isNetworkAvaliable(UeApp.getAppContext())) {

            show_tips.setVisibility(View.VISIBLE);
        } else {
            show_tips.setVisibility(View.GONE);
            getTab();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.show_tip:
                show_tips.setVisibility(View.GONE);
                if (mTitleList.size() > 0) {
                    getNewList("1", cloumId);
                } else {
                    getTab();
                }
                break;
        }
    }

    private void onLoad() {
        vlist.stopRefresh();
        vlist.stopLoadMore();
        Date data = new Date(System.currentTimeMillis());
        vlist.setRefreshTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA).format(data));
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        vlist.setPullLoadEnable(true);
        pageNum = 0;
        getNewList("1", cloumId);
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        vlist.setPullRefreshEnable(true);
        pageNum++;
        getNewList("2", cloumId);
    }

    AdapterView.OnItemClickListener clickItem = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            NewsModel model = newsList.get(arg2 - 1);
            Intent aboutIntent = new Intent(getActivity(), WebViewActivity.class);
            aboutIntent.putExtra("title", "新闻资讯");
            aboutIntent.putExtra("show", "1");
            aboutIntent.putExtra("model", model);
            aboutIntent.putExtra("url", model.getHttpurl());
            startActivity(aboutIntent);
        }

    };

    public void getTab() {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        JSONObject jsondata = new JSONObject();
        parmas.put("jsonText", jsondata.toString());
        NewsService.getcolumnList(context, parmas, new ResponseCallback<NewsTabModelResult>() {
            @Override
            public void onSuccess(NewsTabModelResult accountModel) {
                mTitleList.clear();
                mTitleList.addAll(accountModel.getList());
                if (mTitleList.size() < 4) {
                    mTabLayout.setTabMode(TabLayout.MODE_FIXED);
                } else {
                    mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                }
                for (int i = 0; i < mTitleList.size(); i++) {
                    NewsTableModel model = mTitleList.get(i);

                    if (i == 0) {
                        mTabLayout.addTab(mTabLayout.newTab().setText(model.getName()), true);
                    } else {
                        mTabLayout.addTab(mTabLayout.newTab().setText(model.getName()));
                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }

    public void getNewList(final String refreshType, String cloumId) {
        Map<String, Object> parmas = new HashMap<>();
        parmas.put("device_type", Constant.device_type);
        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
        try {
            JSONObject jsondata = new JSONObject();
            jsondata.put("pageNumber", pageNum);
            jsondata.put("pageSize", pageSize);
            parmas.put("jsonText", jsondata.toString());
        } catch (JSONException e) {
        }
        NewsService.getNewList(context, parmas, cloumId, new ResponseCallback<NewsModelResult>() {
            @Override
            public void onSuccess(NewsModelResult newsModelResult) {
                onLoad();

                if (newsModelResult != null) {
                    if (newsModelResult.getList() != null||newsModelResult.getList().size()>0) {
                        show_tips.setVisibility(View.GONE);
                        switch (refreshType) {
                            case "1":
                                newsList.clear();
                                newsList.addAll(newsModelResult.getList());
                                if (newsModelResult.getList().size()<= pageSize) {
                                    vlist.removeFooterView();
                                    vlist.setPullLoadEnable(false);
                                } else {
                                    vlist.showFooterView();
                                    vlist.setPullLoadEnable(true);
                                }
                                break;
                            case "2":
                                newsList.addAll(newsModelResult.getList());
                                if (newsModelResult.getList().size() <= pageSize) {
                                    vlist.removeFooterView();
                                    vlist.setPullLoadEnable(false);
                                }
                                break;
                        }
                        newsAdapter.notifyDataSetChanged();
                    } else {
                        show_tips.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                show_tips.setVisibility(View.VISIBLE);
                if (newsAdapter != null) {
                    newsAdapter.list.clear();
                    newsAdapter.notifyDataSetChanged();
                }
            }
        });
    }
}
